#include "commandexecutor.h"
#include <QDebug>
#include <QEventLoop>

CommandExecutor::CommandExecutor(QString cmd, QObject *parent) : QObject(parent)
{    
    qDebug() << cmd;
    this->cmd = cmd;
    process = new QProcess();
    connect(process , SIGNAL(readyReadStandardOutput()) , this , SLOT(onReadStandardOutput()));
    connect(process , SIGNAL(readyReadStandardError()) , this , SLOT(onReadStandardError()));
    connect(process , SIGNAL(finished(int, QProcess::ExitStatus)) , this , SLOT(onFinished(int, QProcess::ExitStatus)));
}

CommandExecutor::~CommandExecutor()
{
    if(process){
        process->deleteLater();
    }
}

/**
 * 1. 执行apt install
 */
void CommandExecutor::start()
{
    process->start(cmd);
    qDebug() << cmd << " started";
}

int CommandExecutor::getExitCode() const
{
    return exitCode;
}

QString CommandExecutor::getStdout()
{
    return cmdStdout;
}

QString CommandExecutor::getStderr()
{
    return cmdStderr;
}

QString CommandExecutor::exec(QString cmd)
{
    CommandExecutor ce(cmd);
    QEventLoop eventloop;
    connect(&ce, SIGNAL(finishedEvent()), &eventloop, SLOT(quit()));
    ce.start();
    qDebug() << "eventLoop executing";
    eventloop.exec();
    qDebug() << "eventLoop executed";
    if(ce.getExitCode() == 0){
        return ce.getStdout();
    }
    else{
        return ce.getStderr();
    }
}

void CommandExecutor::onReadStandardOutput()
{
    QString outStr = QString::fromUtf8(process->readAllStandardOutput().data());
    qDebug() << QString("stdout: %1").arg(outStr);
    cmdStdout.append(outStr);
}

void CommandExecutor::onReadStandardError()
{
    QString errStr = QString::fromUtf8(process->readAllStandardError().data());
    qDebug() << QString("stderr: %1").arg(errStr);
    cmdStderr.append(errStr);
}


void CommandExecutor::onFinished(int exitCode, QProcess::ExitStatus)
{
    this->exitCode = exitCode;
    qDebug() << "finished" << exitCode;
    emit finishedEvent();//向上传递
    qDebug() << "emit finishedEvent";
}
